package cn.lwy.example.niit_race.config;

import cn.lwy.example.niit_race.pojo.SysUser;
import cn.lwy.example.niit_race.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class CustomUserDetailService implements UserDetailsService {

    @Autowired
    private LoginService loginService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //通过username获取用户信息
        SysUser user = loginService.findUserByName(username);
        System.out.println(user);
        System.out.println(loginService.findRoleById(user.getRoleId()));
        if(user == null) {
            throw new UsernameNotFoundException("not found");
        }


        //定义权限列表.
        List<GrantedAuthority> authorities = new ArrayList<>();
        // 用户可以访问的资源名称（或者说用户所拥有的权限） 注意：必须"ROLE_"开头
        authorities.add(new SimpleGrantedAuthority("ROLE_"+loginService.findRoleById(user.getRoleId()).getRole()));


        UserDetails userDetails = new User(user.getName(), user.getPassword(), authorities);
        return userDetails;
    }
}
